<template>
    <div class="cart">
        <div class="header">
            <van-nav-bar
                fixed
                :title="isManage?'购物车':'管理购物车'"
                :right-text="isManage?'管理':'取消'"
                left-arrow
                @click-left="onClickHeaderLeft"
                @click-right="onClickHeaderRight"
            />
        </div>
        <div class="mainArea">
            <div class="cartShopItem" v-for="(shop,index) in userCartList" :key="shop.shop_id">
                <div class="item_head">
                    <van-radio :checked="shop.shopChecked" @click="shopCheckAll(shop)">
                        <div class="item_head_shop">
                            <div class="item_head_shop_left"><span class="shop_name">{{shop.shop_info.name}}</span><van-icon name="arrow" color="#aaa" /></div>
                            <div class="item_head_shop_right">
                                <div class="shop_info">
                                    <span>月售{{shop.shop_info.sales_monthly}}</span>
                                    <span>{{shop.shop_info.delivery_duration}}分钟</span>
                                </div>
                                <div class="deleteBtn" v-if="isManage" @click.stop="deleteShopCartFun(shop.shop_id)">
                                    <van-icon name="delete-o" color="#aaa" />
                                </div>
                            </div>
                        </div>
                    </van-radio>
                </div>
                <div class="food_tags">
                    <van-tag 
                        color="#7232dd" 
                        plain 
                        type="primary"
                        v-for="(tag,index) in shop.shop_info.discount.activities[1].value"
                        :key="index"
                    >{{tag}}</van-tag>
                </div>
                <div class="foodItemGroup">
                    <van-checkbox-group v-model="shop.foodItemCheckedGroup">
                        <van-checkbox @click="foodItemCheckedTurn(shop)" :name="food._id" label-disabled v-for="(food,index) in shop.children" :key="food._id">
                            <div class="foodItem">
                                <div class="foodImg"><div class="img"><img src="@/assets/img/shop_detail/food/food.jpeg" alt=""></div></div>
                                <div class="foodInfo">
                                    <div class="foodInfo_top">
                                        <div class="foodName">{{food.food_id.foodName}}</div>
                                        <div class="foodSpec" v-for="(spec,index) in food.food_id.specifications" :key="index">{{spec}}</div>
                                    </div>
                                    <div class="foodInfo_bottom">
                                        <div class="price">
                                            <span>¥{{parseFloat(food.food_id.foodPrice * parseInt(food.foodNum)).toFixed(2)}}</span>
                                        </div>
                                        <div class="stepper">
                                            <van-stepper 
                                                v-model="food.foodNum" 
                                                min="0" 
                                                max="99" 
                                                integer 
                                                button-size="20"
                                                :disabled="isManage == false"
                                                @change="foodStepperNumChange(food)" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </van-checkbox>
                    </van-checkbox-group>
                </div>
                <div class="shopSettle" v-if="shop.foodItemCheckedGroup.length && isManage">
                    <div class="shopSettle_container">
                        <div class="pack_fee_area">
                            <span>包装费</span><span class="pack_fee">¥{{parseFloat(shop.pack_fee).toFixed(1)}}</span>
                        </div>
                        <div class="discount_price_area" v-if="shop.checkedDiscount.length">
                            <span>店铺满{{shop.checkedDiscount[0]}}减{{shop.checkedDiscount[1]}}</span><span class="discount_price">-¥{{shop.checkedDiscount[1]}}</span>
                        </div>
                        <div class="settle_area">
                            <div class="price_area">
                                <div class="discount_price_area" v-if="shop.checkedDiscount.length"><span>已优惠</span><span class="discount_price">¥<span>{{shop.checkedDiscount[1]}}</span></span></div>
                                <div class="total_total_area">
                                    <div class="total"><span>合计：</span><span class="total_price">¥<span>{{parseFloat(shop.actuallyTotalPrice).toFixed(2)}}</span></span></div>
                                    <div class="delivery_fee">另需配送费¥{{shop.shop_info.delivery_fee}}</div>
                                </div>
                            </div>
                            <div class="settleBtn_area">
                                <van-button class="footerBtn" v-if="isManage" color="#02b6fd" round >去结算</van-button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="footer">
            <van-radio :checked="allShopChecked" @click="allShopCheckAll">全选</van-radio>
            <div class="footer_right">
                <div class="priceTotalCount" v-if="isManage">
                    <span>合计:</span>
                    <span class="totalPrice">¥<span class="price">{{parseFloat(allFoodCheckPrice).toFixed(2)}}</span></span>
                </div>
                <van-button class="footerBtn" v-if="isManage"
                    :color="allShopCheckGroup.length?'#02b6fd':'#333'"
                    round 
                    :disabled="allShopCheckGroup.length?false:true"
                >
                    一键结算
                    <span v-if="allShopCheckGroup.length > 1">{{allFoodCheckNum}}个商品</span>
                </van-button>
                <van-button class="footerBtn" v-else
                    :type="allShopCheckGroup.length?'danger':'default'" 
                    :plain="allShopCheckGroup.length?true:false"
                    round 
                    :disabled="allShopCheckGroup.length?false:true"
                >
                    删除
                    <span class="deleteNum" v-if="allShopCheckGroup.length">{{allShopCheckGroup.length}}个商品</span>
                </van-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getUserCart, modifyCartNum, deleteFoodCart} from '@/api/cart'
import { computed, onMounted, reactive, ref, toRefs, watch, inject } from 'vue'
import { showConfirmDialog, showLoadingToast, showNotify, closeToast } from 'vant';
import { useRoute } from 'vue-router';
import { deleteShopCart } from '@/api/cart';
export default {
    name:'Cart',
    setup(){
        // 页面刷新的方法
        const reload = inject('reload');
        // 返回上一页
        const onClickHeaderLeft = () => history.back();
        // 管理 或 取消管理
        const isManage = ref(true);  // 管理 / 取消管理
        const onClickHeaderRight = () => {
            isManage.value = !isManage.value;
            console.log(allShopCheckGroup.value.length)
        };



        // 整个购物车 数据 处理-安装店铺分类成一个数据
        const handlerData = (arr) => {
            let tempArr = [];
            let endData = [];
            for(let i = 0; i<arr.length; i++){
                if(tempArr.indexOf(arr[i].shop_id._id) === -1){
                    endData.push({
                        shop_id:arr[i].shop_id._id,
                        shop_info:arr[i].shop_id,
                        shopChecked:false,
                        foodItemCheckedGroup:[],
                        children:[arr[i]],
                        totalNum:0,
                        totalPrice:0,
                        actuallyTotalPrice:0,
                        checkedDiscount:[],
                        discount:[],
                        pack_fee:0
                    });
                    tempArr.push(arr[i].shop_id._id);
                }
                else{
                    for(let j = 0; j<endData.length; j++){
                        if(endData[j].shop_id == arr[i].shop_id._id){
                            endData[j].children.push(arr[i]);
                            break;
                        }
                    }
                }
            }
            // console.log('endData',endData)
            return endData;
        }
        // 店铺 价格数量优惠计算
        const shopCalculate = (shop) => {
            // 数量，价格计算
            shop.pack_fee = 0;
            shop.totalPrice = 0;
            shop.actuallyTotalPrice = 0;
            shop.checkedDiscount = [];
            shop.totalNum = 0;
            if(shop.foodItemCheckedGroup.length>0){
                for(let i = 0; i<shop.foodItemCheckedGroup.length; i++){
                    let food_id = shop.foodItemCheckedGroup[i];
                    for(let j = 0; j<shop.children.length; j++){
                        let food = shop.children[j];
                        if(food_id == food._id){
                            let food_pack_fee = food.foodNum * food.food_id.pack_fee;
                            shop.pack_fee += food_pack_fee;
                            shop.totalNum += parseInt(food.foodNum);
                            shop.totalPrice = shop.totalPrice + food.foodNum * food.food_id.foodPrice + food_pack_fee;
                            shop.actuallyTotalPrice = shop.totalPrice;
                        }
                    }

                }
                // 满减计算
                for(let j = shop.discount.length-1; j>=0&&shop.foodItemCheckedGroup.length>0; j--){
                    let max = shop.discount[j][0];
                    let min = shop.discount[j][1];
                    console.log('max',max,'min',min);
                    if(shop.totalPrice >= max){
                        shop.actuallyTotalPrice = parseFloat(shop.actuallyTotalPrice - min).toFixed(2);
                        shop.checkedDiscount = shop.discount[j];
                        break;
                    }
                }
            }
            // console.log('shop.pack_fee',shop.pack_fee)
            // console.log(shop.totalPrice)
            // console.log(shop.actuallyTotalPrice)
            // console.log(shop.checkedDiscount)
            // console.log(shop.totalNum)
        }
        // 整个购物车 价格数量计算
        const allShopCalculate = () => {
            allFoodCheckNum.value = 0;
            allFoodCheckPrice.value = 0;
            for(let i = 0; i<userCartList.value.length; i++){
                let shop = userCartList.value[i];
                allFoodCheckNum.value = parseInt(allFoodCheckNum.value + shop.totalNum);
                allFoodCheckPrice.value += parseFloat(shop.actuallyTotalPrice);
            }
            
            allFoodCheckPrice.value = parseFloat(allFoodCheckPrice.value).toFixed(2);
            // console.log(allFoodCheckNum.value)
            // console.log(allFoodCheckPrice.value)
        }



        // 整个购物车 数据
        const data = reactive({userCartList:[]})
        const { userCartList } = toRefs(data);
        // 获取整个购物车 方法
        const getUserCartReq = () => {
            getUserCart({
                user_id:localStorage.getItem('userId')
            }).then(res=>{
                // console.log(res.data)
                userCartList.value = handlerData(res.data);
                // console.log(userCartList.value);
                for(let i = 0; i<userCartList.value.length; i++){
                    let shop = userCartList.value[i];
                    let discount = shop.shop_info.discount.activities.filter(item=>{return item.name=='满减优惠'})[0].value;
                    let newDiscount = [];
                    discount.forEach(item=>{
                        newDiscount.push(item.split('减'));
                    })
                    shop.discount = newDiscount;
                }
                console.log(userCartList.value);
            }).catch(error=>{
                console.log(error);
            })
        }
        onMounted(()=>{
            // 发送请求
            getUserCartReq();
        })
        // 所有选中的商品id
        const allShopCheckGroup = computed(()=>{
            let groupArr = [];
            for(let i = 0; i<userCartList.value.length; i++){
                let shop = userCartList.value[i];
                for(let j = 0; j<shop.foodItemCheckedGroup.length; j++){
                    let food = shop.foodItemCheckedGroup[j];
                    groupArr.push(food);
                }
            }
            return groupArr;
        });
        watch(allShopCheckGroup,(newVal,oldVal)=>{
            console.log('allShopCheckGroup',newVal);
        })
        // 整个购物车 选中的商品的数量
        const allFoodCheckNum = ref(0);
        // 管理 整个购物车 选中的商品的数量
        const allFoodCheckDeleteNum = ref(allShopCheckGroup.value.length);
        // 整个购物车 选中的商品的总价
        const allFoodCheckPrice = ref(0);
        // 整个购物车 是否全选 按钮状态
        const allShopChecked = computed(()=>{
            let shopCheckedNum = userCartList.value.filter(item=>{
                return item.shopChecked == true;
            })
            if(shopCheckedNum.length == userCartList.value.length) return true;
            else return false;
        });

        

        // 删除指定店铺的购物车
        const deleteShopCartFun = (shop_id) => {
            console.log(shop_id);
            showConfirmDialog({
                    title: '确认清空店铺内所有商品？',
                })
                .then(() => {
                    // on confirm
                    console.log('确认');
                    showLoadingToast({ forbidClick: true });
                    // 删除购物车中 指定的店铺
                    deleteShopCart({
                        user_id:localStorage.getItem('userId'),
                        shop_id:shop_id
                    }).then(res=>{
                        console.log(res)
                        if(res.code == '6600'){
                            setTimeout(() => {
                                closeToast();
                                reload();
                            }, 500);
                        }
                        else{
                            showNotify({ type: 'warning', message: res.message });
                        }
                    }).catch(error=>{
                        console.log(error)
                    })
                })
                .catch(() => {
                    // on cancel
                    console.log('取消');
                });
                return;
            
        }
        // 步进器数量变化
        // =0 删除; !=0 修改;
        const foodStepperNumChange = (food) => {
            console.log(food)
            if(food.foodNum == 0){
                showConfirmDialog({
                    title: '确认删除该商品？',
                })
                .then(() => {
                    // on confirm
                    console.log('确认');
                    showLoadingToast({ forbidClick: true });
                    // 删除购物车信息
                    deleteFoodCart({
                        id:food._id
                    }).then(res=>{
                        console.log(res)
                        // window.location.reload();
                        if(res.code == '6500'){
                            setTimeout(() => {
                                closeToast();
                                reload();
                            }, 500);
                        }
                        else{
                            showNotify({ type: 'warning', message: res.message });
                        }
                    }).catch(error=>{
                        console.log(error)
                    })

                })
                .catch(() => {
                    // on cancel
                    console.log('取消')
                    food.foodNum = 1
                });
                return;
            } 
            else{
                // 修改购物车信息  数量
                modifyCartNum({
                    id:food._id,
                    num:food.foodNum
                }).then(res=>{
                    console.log(res)
                }).catch(error=>{
                    console.log(error);
                })
            }
        }
        // 单个商品选中
        const foodItemCheckedTurn = (shop) => {
            // 判断该店铺是否全选，是则取消全选，否则全选
            if(shop.children.length == shop.foodItemCheckedGroup.length) shop.shopChecked = true;
            else shop.shopChecked = false;

            // 店铺 价格数量优惠计算
            shopCalculate(shop);
            // 整个购物车 价格数量计算
            allShopCalculate();
        }
        // 店铺全选
        const shopCheckAll = (shop) => {
            if(shop.shopChecked) {
                // 取消全选
                shop.shopChecked = false;
                shop.foodItemCheckedGroup.splice(0,shop.foodItemCheckedGroup.length);
            }
            else{
                // 全选
                shop.shopChecked = true;
                shop.children.forEach(item=>{
                    if(shop.foodItemCheckedGroup.indexOf(item._id) == -1) shop.foodItemCheckedGroup.push(item._id)
                })
            }
            
            // 店铺 价格数量优惠计算
            shopCalculate(shop);
            // 整个购物车 价格数量计算
            allShopCalculate();
        }
        // 底部全选
        const allShopCheckAll = () => {
            if(allShopChecked.value){
                userCartList.value.forEach(item=>{
                    item.shopChecked = true;
                    shopCheckAll(item);
                })
            }
            else{
                userCartList.value.forEach(item=>{
                    item.shopChecked = false;
                    shopCheckAll(item);
                })
            }
            
            // 店铺 价格数量优惠计算
            for(let i = 0; i<userCartList.value.length; i++){
                let shop = userCartList.value[i];
                shopCalculate(shop);
            }
            // 整个购物车 价格数量计算
            allShopCalculate();
        }

        return {
            isManage,
            onClickHeaderLeft,
            onClickHeaderRight,
            userCartList,
            allShopCheckGroup,
            allFoodCheckNum,
            allFoodCheckDeleteNum,
            allFoodCheckPrice,
            allShopChecked,
            deleteShopCartFun,
            foodStepperNumChange,
            foodItemCheckedTurn,
            shopCheckAll,
            allShopCheckAll,
        }
    },
}
</script>

<style>
:root{
    --van-nav-bar-height : 48px;
    --van-nav-bar-icon-color:rgb(101, 101, 101);
    --van-nav-bar-arrow-size:22px;
    --van-nav-bar-text-color:#000;
    --van-nav-bar-background:#f5f5f5;
}
.cart .mainArea{
    box-sizing: border-box;
    width: 100%;
    padding: 55px 15px 48px 15px;
    min-height: 100vh;
    background: #f5f5f5;
}

/* ------------------ */
.cart .mainArea .cartShopItem{
    margin-bottom: 10px;
    padding: 10px 15px;
    background: #fff;
    border-radius: 0.5rem;
    box-shadow: 0 5px rgba(0, 0, 0, 0.01);
    display: flex;
    flex-direction: column;
}
.cart .mainArea .cartShopItem .van-radio__label,.van-checkbox__label{flex-grow: 1;}
.cart .mainArea .cartShopItem .item_head_shop{display: flex;align-items: center;justify-content: space-between;}
.cart .mainArea .cartShopItem .item_head_shop .van-icon{font-size: 12px;margin-left: 5px;}
.cart .mainArea .cartShopItem .item_head_shop_left{
    width: 50%;
    flex-shrink: 0;
    display: flex;
    align-items: center;
}
.cart .mainArea .cartShopItem .item_head_shop_left span.shop_name{
    display: inline-block;
    max-width: 85%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 14px;
    font-weight: 600;
}
.cart .mainArea .cartShopItem .item_head_shop_right{display: flex;align-items: center;justify-content: flex-end;}
.cart .mainArea .cartShopItem .item_head_shop_right span{color: #aaa;font-size: 12px;margin-right: 5px;}
.cart .mainArea .cartShopItem .item_head_shop_right .deleteBtn{line-height: 1;}
.cart .mainArea .cartShopItem .food_tags{margin-top: 10px;margin-left: 28px;}
.cart .mainArea .cartShopItem .foodItemGroup{width: 100%;}
.cart .mainArea .cartShopItem .foodItemGroup .van-checkbox{margin: 10px 0;width: 100%;}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem{display: flex;align-items: center;height: 73px;}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodImg{width: 25%;margin-right: 10px;  }
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodImg .img{
    width: 100%;
    height: 0;
    padding-bottom: 100%;
    border-radius: 0.5rem;
    overflow: hidden;
    position: relative;
}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodImg .img img{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodInfo{
    width: 75%;
    height: 100%;
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodInfo .foodInfo_top .foodName{font-size: 14px;font-weight: 600;}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodInfo .foodInfo_top .foodSpec{font-size: 12px;color: #aaa;}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodInfo .foodInfo_bottom{display: flex;justify-content: space-between;align-items: center;}
.cart .mainArea .cartShopItem .foodItemGroup .foodItem .foodInfo .foodInfo_bottom .price{font-size: 12px;font-weight: 600;}


/* ------------------ */
.cart .mainArea .cartShopItem .shopSettle{margin-left: 28px;border-top: 1px solid #f5f5f5;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container{width: 100%;display: flex;flex-direction: column;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container>.pack_fee_area,
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container>.discount_price_area{
    margin: 5px 0 3px;
    font-size: 13px;
    color: #000;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container>.pack_fee_area span.pack_fee{font-weight: 600;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container>.discount_price_area span.discount_price{color: red;font-weight: 600;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area{
    margin-top: 5px;
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area{
    display: flex;
    justify-content: flex-end;
    align-items: flex-start;
    font-size: 13px;
}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area .discount_price_area span.discount_price{
    margin-left: 5px;
    color: red;
    font-weight: 600;
    font-size: 12px;
}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area .discount_price_area span.discount_price>span{font-size: 13px;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area .total_total_area{
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-end;
    margin-left: 10px;
}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area .total_total_area span.total_price{color: red;font-weight: 600;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area .total_total_area .delivery_fee{margin-top: 2px;font-size: 12px;color: #aaa;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .price_area .total_total_area span.total_price>span{font-size: 15px;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .settleBtn_area{margin-left: 10px;}
.cart .mainArea .cartShopItem .shopSettle .shopSettle_container .settle_area .settleBtn_area .van-button{height: 35px;min-width: 90px;}


/* ------------------ */
.cart .footer{
    position: fixed;
    bottom: 0;
    left: 0;
    box-sizing: border-box;
    padding: 0 15px;
    width: 100%;
    height: 60px;
    background: #fff;
    font-size: 13px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.cart .footer .footer_right{display: flex;justify-content: flex-end;align-items: center;}
.cart .footer .footer_right .priceTotalCount{margin-right: 10px;}
.cart .footer .footer_right .totalPrice{color: red;}
.cart .footer .footer_right .totalPrice .price{font-size: 18px;}
.cart .footer .footer_right .footerBtn{min-width: 110px;}
.van-button__text{display: flex;flex-direction: column;justify-content: center;}
.cart .footer .footer_right .footerBtn .van-button__text span{font-size: 12px;}
</style>